package com.jh.user.service.impl;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.CommonsUtil;
import cn.jh.common.utils.StringUtil;
import com.jh.user.pojo.*;
import com.jh.user.repository.*;
import com.jh.user.service.PlatformService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

@Service
public class PlatformServiceImpl implements PlatformService{

    @Autowired
    private PlatformRepository platformRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private FastSilverPicPathRepository fastSilverPicPathRepository;

    private static Logger LOG = LoggerFactory.getLogger(PlatformServiceImpl.class);

    public List<Platform> queryPlatform(PlatformEntity entity){
        String sql = "select * from t_platform p where 1 = 1";
        if(StringUtils.isNotBlank(entity.getPlatformCode())){
            sql += " and p.platform_code = '" + entity.getPlatformCode() + "'";
        }
        if(StringUtils.isNotBlank(entity.getAgent())){
            sql += " and p.agent = '" + entity.getAgent() + "'";
        }
        if(StringUtils.isNotBlank(entity.getMerchantId())){
            sql += " and p.shop_id = '" + entity.getMerchantId() +"'" ;
        }
        if(StringUtils.isNotBlank(entity.getStaTime())){
            sql += " and p.create_time >= '" + entity.getStaTime() + "'";
        }

        if(StringUtils.isNotBlank(entity.getEndTime())){
            sql += " and p.create_time <= '" +entity.getEndTime() + "' ";
        }

        if(StringUtils.isNotBlank(entity.getState())){
            sql += " and p.state = '" + entity.getState() + "' ";
        }
        sql += " order by p.dial_code_type";
        List<Platform> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Platform.class));
        if (null != list && list.size() > 0) {
            for (Platform platform : list) {
                String shopId = platform.getShopId();
                User user = userRepository.findUserByPhone(shopId);
                if (null != user) {
                    FastSilverPicPath fastSilverPicPath = fastSilverPicPathRepository.queryByUserId(user.getId());
                    if (null == fastSilverPicPath) {
                        // 未提交图片或缺少图片
                        platform.setIsUploadFsPic(1);
                    } else {
//                        long count = fastSilverPicPath.validFSilverPicPath();
//                        if (count != 0) {
                            // 未提交图片或缺少图片
//                            platform.setIsUploadFsPic(1);
//                        } else {
                            // 已全部上传图片
                            platform.setIsUploadFsPic(0);
//                        }
                    }
                }
            }
        }
        return list;
    }

    public int queryAgent(String agent){
        String sql = "select role_id from t_user t left join t_user_role r on r.user_id = t.id and r.role_id = 6 where phone = '" + agent + "'";
        List<Platform> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Platform.class));
        if(list.size() > 0){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public Page<Platform> queryPlatFromByShopId(String mobilePhone, Pageable pageable) {
        return platformRepository.queryPlatFromByShopId(mobilePhone, pageable);
    }

    public List<Platform> selectPlatform(String platformCode){
        String sql = "select platform_code as platformCode,platform_type as platformType,state,agent,shop_id as merchantId,dial_code_type as dialCodeType,qrc_code as qrcCode,create_time as createTime,create_by as createBy from t_platform p where 1 = 1";
        if(StringUtils.isNotBlank(platformCode)){
            sql += " and p.platform_code in (" + platformCode + ")";
        }
        sql += " order by p.dial_code_type";
        List<Platform> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Platform.class));
        return list;
    }

    @Transactional
    public void addPlatform(List<Platform> platform){
        platformRepository.save(platform);
    }

    public String selectPlatform(Platform platform){
        return platformRepository.selectPlatform();
    }

    @Transactional
    public void updatePlatform(Platform platform,String type) throws ServiceException{

        String sql = "update t_platform p set  ";

        if(type.equalsIgnoreCase("2")){
            if(StringUtils.isNotBlank(platform.getAgent())){
                sql += " agent = '" + platform.getAgent() + "' ";
            }
        }else{
            if(StringUtils.isNotBlank(platform.getShopId())){
                sql += " shop_id = '" + platform.getShopId() + "' ";
            }
        }

        if(StringUtils.isNotBlank(platform.getDialCodeType())){
            sql += " , dial_code_type = '"+platform.getDialCodeType() + "' ";
        }

        if(StringUtils.isNotBlank(platform.getState())){
            sql += " , state = '" + platform.getState() + "' ";
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(platform.getIntroducerPhone())) {
            sql += " , introducer_phone = '" + platform.getIntroducerPhone() + "' ";
        }

        sql += "  where p.platform_code = " + platform.getPlatformCode();
        jdbcTemplate.update(sql);
    }

    public List<Platform> queryPlatformList(int pageNumber,PlatformEntity entity){

//        String sql = "select platform_code as platformCode,platform_type as platformType,state,agent,shop_id as merchantId,dial_code_type as dialCodeType,qrc_code as qrcCode,create_time as createTime,create_by as createBy from t_platform p where 1 = 1";
        String sql = "select * from t_platform p where 1 = 1";
        if(StringUtils.isNotBlank(entity.getPlatformCode())){
            sql += " and p.platform_code = '" + entity.getPlatformCode() + "'";
        }
        if(StringUtils.isNotBlank(entity.getAgent())){
            sql += " and p.agent = '" + entity.getAgent() + "'";
        }
        if(StringUtils.isNotBlank(entity.getMerchantId())){
            sql += " and p.shop_id = '" + entity.getShopPhone()+"'" ;
        }
        if(StringUtils.isNotBlank(entity.getStaTime())){
            sql += " and p.create_time >= '" + entity.getStaTime() + "'";
        }

        if(StringUtils.isNotBlank(entity.getEndTime())){
            sql += " and p.create_time <= '" +entity.getEndTime() + "' ";
        }

        if(StringUtils.isNotBlank(entity.getState())){
            sql += " and p.state = '" + entity.getState() + "' ";
        }

        if (StringUtils.isNotBlank(entity.getShopPhone())) {
            sql += " and p.shop_id = '" + entity.getShopPhone() + "' ";
        }

        int start = 0;
        if(pageNumber > 1){
            start = (pageNumber-1) * 20;
        }
        sql += " order by p.dial_code_type LIMIT " + start + ",20";
        List<Platform> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Platform.class));
        return list;
    }

    public int queryPlatformCount(PlatformEntity entity)throws SQLException{
        String sql = "select platform_code as platformCode,platform_type as platformType,state,agent,shop_id as merchantId,dial_code_type as dialCodeType,qrc_code as qrcCode,create_time as createTime,create_by as createBy from t_platform p where 1 = 1";
        if(StringUtils.isNotBlank(entity.getPlatformCode())){
            sql += " and p.platform_code = '" + entity.getPlatformCode() + "'";
        }
        if(StringUtils.isNotBlank(entity.getAgent())){
            sql += " and p.agent = '" + entity.getAgent() + "'";
        }
        if(StringUtils.isNotBlank(entity.getShopPhone())){
            sql += " and p.shop_id = '" + entity.getShopPhone() +"'" ;
        }
        if(StringUtils.isNotBlank(entity.getAgent())){
            sql += " and p.agent = '" + entity.getAgent() +"'" ;
        }
        if(StringUtils.isNotBlank(entity.getStaTime())){
            sql += " and p.create_time >= '" + entity.getStaTime() + "'";
        }

        if(StringUtils.isNotBlank(entity.getEndTime())){
            sql += " and p.create_time <= '" +entity.getEndTime() + "' ";
        }

        if(StringUtils.isNotBlank(entity.getState())){
            sql += " and p.state = '" + entity.getState() + "' ";
        }
        sql += " order by p.dial_code_type ";
        List<Platform> list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Platform.class));
        return list.size();
    }

    public Platform findPlatform(String platformCode, String state){
        return platformRepository.findByPlatformCodeAndState(platformCode,state);
    }

    @Transactional
    @Override
    public void bmsUpdatePlatForm(String fromAgent, String toAgent) throws ServiceException {
        /* 1、查询toAgent用户基本信息 */
        User toUser = userRepository.getByPhone(toAgent);
        if (toUser == null) {
            throw new ServiceException("变更台码代理失败，未查询到" + toAgent + "用户信息！");
        }

        /* 2、查询toAgent用户角色信息 */
        long userId = toUser.getId();
        UserRole userRole = userRoleRepository.findUserRoleByUserId(userId);
        if (userRole == null) {
            throw new ServiceException("变更台码代理失败，未查询到" + toAgent + "用户角色信息！");
        }
        long roleId = userRole.getRoleId();
        Role role = roleRepository.findById(roleId);
        if (role == null) {
            throw new ServiceException("变更台码代理失败，未查询到" + toAgent + "用户角色！");
        }
        if (!CommonConstants.ROLE_CODE_06.equals(role.getRolecode())) {
            throw new ServiceException("变更台码代理失败，" + toAgent + "用户角色为"+ CommonsUtil.getRoleName(role.getRolecode()) +"！");
        }

        /* 3、查询fromAgent用户台码信息 */
        List<Platform> platformList = platformRepository.findByAgent(fromAgent);
        if (platformList == null || platformList.size() == 0) {
            throw new ServiceException("变更台码代理失败，未查询到" + fromAgent + "用户台码信息！");
        }

        /* 4、变更该台码的台卡代理 */
        for (Platform platform : platformList) {
            int result = platformRepository.updatePlatform(toAgent, platform.getPlatformId());
            LOG.info("变更该台码的台码代理结果：result = " + result + "，（1：成功，0：失败）" + "，变更前agent = " + platform.getAgent());
        }
    }

    @Override
    public String getUserIdByPlatform(String agent) throws ServiceException {
        StringBuffer sb = new StringBuffer();
        List<Platform> platformList = platformRepository.getPlatform(agent);
        if (null == platformList || platformList.size() == 0) {
            throw new ServiceException("获取台码信息失败！");
        }
        for (int i = 0; i < platformList.size(); i++) {
            String phone = platformList.get(i).getShopId();
            if (StringUtils.isNotEmpty(phone)) {
                User user = userRepository.getByPhone(phone);
                if (null == user) {
                    throw new ServiceException("获取用户信息失败！");
                }
                long userId = user.getId();
                sb.append(userId + ",");
            }
        }
        return sb.toString().substring(0, sb.length() - 1);
    }
}
